"""
代码闯关挑战模块 - 更新版本
提供拖拽式代码片段闯关功能，与知识可视化主题关联
每个Rust知识点作为一个关卡
"""

import json
import os
from typing import Dict, List, Optional, Any
from datetime import datetime
import random

class CodeChallengeManager:
    def __init__(self, data_dir="challenge_data"):
        self.data_dir = data_dir
        self.challenges_file = os.path.join(data_dir, "challenges.json")
        self.user_progress_file = os.path.join(data_dir, "user_progress.json")
        self._ensure_data_directory()
        self.challenges = self._load_challenges()
        self.user_progress = self._load_user_progress()
    
    def _ensure_data_directory(self):
        """确保数据目录存在"""
        if not os.path.exists(self.data_dir):
            os.makedirs(self.data_dir)
    
    def _load_challenges(self) -> Dict:
        """加载关卡数据"""
        if os.path.exists(self.challenges_file):
            try:
                with open(self.challenges_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception as e:
                print(f"加载关卡数据失败: {e}")
                return self._create_default_challenges()
        else:
            challenges = self._create_default_challenges()
            self._save_challenges(challenges)
            return challenges
    
    def _load_user_progress(self) -> Dict:
        """加载用户进度"""
        if os.path.exists(self.user_progress_file):
            try:
                with open(self.user_progress_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception as e:
                print(f"加载用户进度失败: {e}")
                return {}
        return {}
    
    def _save_challenges(self, challenges: Dict):
        """保存关卡数据"""
        try:
            with open(self.challenges_file, 'w', encoding='utf-8') as f:
                json.dump(challenges, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存关卡数据失败: {e}")
    
    def _save_user_progress(self):
        """保存用户进度"""
        try:
            with open(self.user_progress_file, 'w', encoding='utf-8') as f:
                json.dump(self.user_progress, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存用户进度失败: {e}")
    
    def _create_default_challenges(self) -> Dict:
        """创建默认关卡数据 - 每个Rust知识点作为一个关卡"""
        return {
            "ownership": {
                "title": "所有权系统",
                "description": "通过拖拽代码片段学习Rust所有权概念",
                "levels": [
                    {
                        "id": "ownership_1",
                        "title": "所有权基础",
                        "description": "理解所有权的转移规则",
                        "difficulty": 1,
                        "code_template": [
                            "fn main() {",
                            "    let s1 = String::from(\"hello\");",
                            "    let s2 = _____;",
                            "    println!(\"{}\", s2);",
                            "}"
                        ],
                        "code_fragments": [
                            {"id": "frag1", "code": "s1", "correct": False, "hint": "这会导致编译错误，因为s1被移动了"},
                            {"id": "frag2", "code": "s1.clone()", "correct": True, "hint": "正确！使用clone创建副本"},
                            {"id": "frag3", "code": "&s1", "correct": False, "hint": "这只是一个引用，不能赋值给String"},
                            {"id": "frag4", "code": "String::from(\"hello\")", "correct": True, "hint": "也可以创建新的String"}
                        ],
                        "correct_answer": ["s1.clone()"],
                        "explanation": "在Rust中，所有权默认是移动的。要使用s1的值，需要clone()创建副本。",
                        "unlocked": True
                    },
                    {
                        "id": "ownership_2", 
                        "title": "函数参数所有权",
                        "description": "理解函数调用中的所有权转移",
                        "difficulty": 2,
                        "code_template": [
                            "fn take_ownership(s: String) {",
                            "    println!(\"{}\", s);",
                            "}",
                            "",
                            "fn main() {",
                            "    let s = String::from(\"hello\");",
                            "    take_ownership(_____);",
                            "}"
                        ],
                        "code_fragments": [
                            {"id": "frag1", "code": "s", "correct": True, "hint": "正确！所有权转移给函数"},
                            {"id": "frag2", "code": "s.clone()", "correct": False, "hint": "不需要clone，直接转移"},
                            {"id": "frag3", "code": "&s", "correct": False, "hint": "函数需要String，不是引用"},
                            {"id": "frag4", "code": "&mut s", "correct": False, "hint": "函数需要String，不是可变引用"}
                        ],
                        "correct_answer": ["s"],
                        "explanation": "函数take_ownership接收String参数，会获得所有权。调用后原变量s失效。",
                        "unlocked": False
                    }
                ]
            },
            "borrowing": {
                "title": "借用检查器",
                "description": "学习Rust的借用规则",
                "levels": [
                    {
                        "id": "borrowing_1",
                        "title": "不可变借用",
                        "description": "理解不可变引用的使用",
                        "difficulty": 1,
                        "code_template": [
                            "fn main() {",
                            "    let s = String::from(\"hello\");",
                            "    let len = calculate_length(_____);",
                            "    println!(\"The length of '{}' is {}.\", s, len);",
                            "}",
                            "",
                            "fn calculate_length(s: _____) -> usize {",
                            "    s.len()",
                            "}"
                        ],
                        "code_fragments": [
                            {"id": "frag1", "code": "s", "correct": False, "hint": "会转移所有权"},
                            {"id": "frag2", "code": "&s", "correct": True, "hint": "正确！使用不可变引用"},
                            {"id": "frag3", "code": "&mut s", "correct": False, "hint": "不需要可变引用"},
                            {"id": "frag4", "code": "&String", "correct": True, "hint": "正确！函数参数类型"}
                        ],
                        "correct_answer": ["&s", "&String"],
                        "explanation": "使用不可变引用&可以在不转移所有权的情况下访问数据。",
                        "unlocked": True
                    },
                    {
                        "id": "borrowing_2",
                        "title": "可变借用",
                        "description": "理解可变引用的使用",
                        "difficulty": 2,
                        "code_template": [
                            "fn main() {",
                            "    let mut s = String::from(\"hello\");",
                            "    change(_____);",
                            "}",
                            "",
                            "fn change(some_string: _____) {",
                            "    some_string.push_str(\", world\");",
                            "}"
                        ],
                        "code_fragments": [
                            {"id": "frag1", "code": "&mut s", "correct": True, "hint": "正确！传递可变引用"},
                            {"id": "frag2", "code": "&s", "correct": False, "hint": "不可变引用不能修改"},
                            {"id": "frag3", "code": "s", "correct": False, "hint": "会转移所有权"},
                            {"id": "frag4", "code": "&mut String", "correct": True, "hint": "正确！函数参数类型"}
                        ],
                        "correct_answer": ["&mut s", "&mut String"],
                        "explanation": "要修改数据，需要使用可变引用&mut。",
                        "unlocked": False
                    }
                ]
            },
            "lifetimes": {
                "title": "生命周期",
                "description": "理解Rust的引用生命周期管理",
                "levels": [
                    {
                        "id": "lifetimes_1",
                        "title": "生命周期基础",
                        "description": "理解引用的生命周期概念",
                        "difficulty": 2,
                        "code_template": [
                            "fn main() {",
                            "    let s1 = String::from(\"hello\");",
                            "    let s2 = String::from(\"world\");",
                            "    let result = longest(_____);",
                            "    println!(\"The longest string is: {}\", result);",
                            "}",
                            "",
                            "fn longest<'a>(s1: &'a str, s2: &'a str) -> &'a str {",
                            "    if s1.len() > s2.len() {",
                            "        _____",
                            "    } else {",
                            "        s2",
                            "    }",
                            "}"
                        ],
                        "code_fragments": [
                            {"id": "frag1", "code": "&s1, &s2", "correct": True, "hint": "正确！传递引用"},
                            {"id": "frag2", "code": "s1", "correct": True, "hint": "正确！返回s1的引用"},
                            {"id": "frag3", "code": "&s1", "correct": False, "hint": "已经在函数参数中使用了&"},
                            {"id": "frag4", "code": "s2", "correct": False, "hint": "根据长度判断，应该返回s1"}
                        ],
                        "correct_answer": ["&s1, &s2", "s1"],
                        "explanation": "使用生命周期参数'a确保返回的引用与输入引用具有相同的生命周期。",
                        "unlocked": True
                    }
                ]
            },
            "traits": {
                "title": "Trait系统",
                "description": "学习Rust的接口和泛型编程",
                "levels": [
                    {
                        "id": "traits_1",
                        "title": "Trait基础",
                        "description": "理解Trait的定义和实现",
                        "difficulty": 2,
                        "code_template": [
                            "trait Summary {",
                            "    fn summarize(&self) -> String;",
                            "}",
                            "",
                            "struct NewsArticle {",
                            "    headline: String,",
                            "    location: String,",
                            "    author: String,",
                            "    content: String,",
                            "}",
                            "",
                            "impl _____ NewsArticle {",
                            "    fn summarize(&self) -> String {",
                            "        format!(\"{}, by {} ({})\", self.headline, self.author, self.location)",
                            "    }",
                            "}",
                            "",
                            "fn main() {",
                            "    let article = NewsArticle {",
                            "        headline: String::from(\"Penguins win the Stanley Cup Championship!\"),",
                            "        location: String::from(\"Pittsburgh, PA, USA\"),",
                            "        author: String::from(\"Iceburgh\"),",
                            "        content: String::from(\"The Pittsburgh Penguins once again are the best hockey team in the NHL.\"),",
                            "    };",
                            "    println!(\"New article available! {}\", article.summarize());",
                            "}"
                        ],
                        "code_fragments": [
                            {"id": "frag1", "code": "Summary for", "correct": True, "hint": "正确！为NewsArticle实现Summary trait"},
                            {"id": "frag2", "code": "Trait", "correct": False, "hint": "语法错误"},
                            {"id": "frag3", "code": "impl", "correct": False, "hint": "需要指定trait名称"},
                            {"id": "frag4", "code": "Summary", "correct": False, "hint": "缺少for关键字"}
                        ],
                        "correct_answer": ["Summary for"],
                        "explanation": "使用impl Trait for Struct语法为结构体实现trait。",
                        "unlocked": True
                    }
                ]
            },
            "error-handling": {
                "title": "错误处理",
                "description": "学习Result和Option类型的使用",
                "levels": [
                    {
                        "id": "error-handling_1",
                        "title": "Result类型基础",
                        "description": "理解Result枚举的使用",
                        "difficulty": 1,
                        "code_template": [
                            "fn divide(numerator: f64, denominator: f64) -> _____<f64, String> {",
                            "    if denominator == 0.0 {",
                            "        Err(String::from(\"Cannot divide by zero\"))",
                            "    } else {",
                            "        _____(numerator / denominator)",
                            "    }",
                            "}",
                            "",
                            "fn main() {",
                            "    match divide(10.0, 2.0) {",
                            "        Ok(result) => println!(\"Result: {}\", result),",
                            "        Err(e) => println!(\"Error: {}\", e),",
                            "    }",
                            "}"
                        ],
                        "code_fragments": [
                            {"id": "frag1", "code": "Result", "correct": True, "hint": "正确！使用Result枚举"},
                            {"id": "frag2", "code": "Option", "correct": False, "hint": "Option不包含错误信息"},
                            {"id": "frag3", "code": "Ok", "correct": True, "hint": "正确！返回Ok变体"},
                            {"id": "frag4", "code": "Some", "correct": False, "hint": "Some是Option的变体"}
                        ],
                        "correct_answer": ["Result", "Ok"],
                        "explanation": "Result<T, E>枚举有两个变体：Ok(T)表示成功，Err(E)表示错误。",
                        "unlocked": True
                    },
                    {
                        "id": "error-handling_2",
                        "title": "Option类型基础",
                        "description": "理解Option枚举的使用",
                        "difficulty": 1,
                        "code_template": [
                            "fn main() {",
                            "    let some_number = Some(5);",
                            "    let some_string = Some(\"a string\");",
                            "",
                            "    let absent_number: Option<i32> = _____;",
                            "",
                            "    match some_number {",
                            "        Some(i) => println!(\"Got a number: {}\", i),",
                            "        None => println!(\"Got nothing\"),",
                            "    }",
                            "}"
                        ],
                        "code_fragments": [
                            {"id": "frag1", "code": "None", "correct": True, "hint": "正确！Option的None变体"},
                            {"id": "frag2", "code": "null", "correct": False, "hint": "Rust没有null"},
                            {"id": "frag3", "code": "Option::None", "correct": True, "hint": "也可以使用完整路径"},
                            {"id": "frag4", "code": "Some(0)", "correct": False, "hint": "这表示有值，不是无值"}
                        ],
                        "correct_answer": ["None"],
                        "explanation": "Option<T>枚举有两个变体：Some(T)表示有值，None表示无值。",
                        "unlocked": False
                    }
                ]
            },
            "closures": {
                "title": "闭包",
                "description": "学习Rust的闭包特性",
                "levels": [
                    {
                        "id": "closures_1",
                        "title": "闭包基础",
                        "description": "理解闭包的定义和使用",
                        "difficulty": 2,
                        "code_template": [
                            "fn main() {",
                            "    let x = 4;",
                            "    ",
                            "    let equal_to_x = |z| z == _____;",
                            "    ",
                            "    let y = 4;",
                            "    ",
                            "    assert!(equal_to_x(y));",
                            "}"
                        ],
                        "code_fragments": [
                            {"id": "frag1", "code": "x", "correct": True, "hint": "正确！闭包可以捕获环境变量"},
                            {"id": "frag2", "code": "4", "correct": True, "hint": "也可以直接使用字面量"},
                            {"id": "frag3", "code": "&x", "correct": False, "hint": "不需要引用"},
                            {"id": "frag4", "code": "z", "correct": False, "hint": "这是参数，不是比较对象"}
                        ],
                        "correct_answer": ["x"],
                        "explanation": "闭包可以捕获其定义环境中的变量。",
                        "unlocked": True
                    }
                ]
            },
            "concurrency": {
                "title": "并发编程",
                "description": "学习Rust的并发特性",
                "levels": [
                    {
                        "id": "concurrency_1",
                        "title": "线程基础",
                        "description": "理解线程的创建和使用",
                        "difficulty": 2,
                        "code_template": [
                            "use std::thread;",
                            "use std::time::Duration;",
                            "",
                            "fn main() {",
                            "    let handle = thread::spawn(|| {",
                            "        for i in 1..10 {",
                            "            println!(\"hi number {} from the spawned thread!\", i);",
                            "            thread::sleep(Duration::from_millis(1));",
                            "        }",
                            "    });",
                            "    ",
                            "    for i in 1..5 {",
                            "        println!(\"hi number {} from the main thread!\", i);",
                            "        thread::sleep(Duration::from_millis(1));",
                            "    }",
                            "    ",
                            "    _____;",
                            "}"
                        ],
                        "code_fragments": [
                            {"id": "frag1", "code": "handle.join()", "correct": True, "hint": "正确！等待线程完成"},
                            {"id": "frag2", "code": "handle.wait()", "correct": False, "hint": "没有wait方法"},
                            {"id": "frag3", "code": "handle.finish()", "correct": False, "hint": "没有finish方法"},
                            {"id": "frag4", "code": "thread::join(handle)", "correct": False, "hint": "语法错误"}
                        ],
                        "correct_answer": ["handle.join()"],
                        "explanation": "使用join()方法等待线程完成，确保主线程不会提前退出。",
                        "unlocked": True
                    }
                ]
            },
            "macros": {
                "title": "宏",
                "description": "学习Rust的宏系统",
                "levels": [
                    {
                        "id": "macros_1",
                        "title": "宏基础",
                        "description": "理解宏的定义和使用",
                        "difficulty": 3,
                        "code_template": [
                            "macro_rules! say_hello {",
                            "    // `()` 表示不接收任何参数。",
                            "    () => ({",
                            "        // `println!` 是宏，所以需要使用 `!`。",
                            "        _____!(\"Hello, World!\");",
                            "    });",
                            "}",
                            "",
                            "fn main() {",
                            "    say_hello!()",
                            "}"
                        ],
                        "code_fragments": [
                            {"id": "frag1", "code": "println", "correct": True, "hint": "正确！使用println宏"},
                            {"id": "frag2", "code": "print", "correct": False, "hint": "print不会换行"},
                            {"id": "frag3", "code": "format", "correct": False, "hint": "format返回字符串，不打印"},
                            {"id": "frag4", "code": "eprintln", "correct": False, "hint": "eprintln打印到标准错误"}
                        ],
                        "correct_answer": ["println"],
                        "explanation": "宏可以定义代码模式，在编译时展开。",
                        "unlocked": True
                    }
                ]
            },
            "pattern-matching": {
                "title": "模式匹配",
                "description": "学习Rust的模式匹配特性",
                "levels": [
                    {
                        "id": "pattern-matching_1",
                        "title": "match表达式基础",
                        "description": "理解match表达式的使用",
                        "difficulty": 1,
                        "code_template": [
                            "fn main() {",
                            "    let number = 13;",
                            "    ",
                            "    _____ number {",
                            "        1 => println!(\"One!\"),",
                            "        2 => println!(\"Two!\"),",
                            "        3 => println!(\"Three!\"),",
                            "        _ => println!(\"Something else!\"),",
                            "    }",
                            "}"
                        ],
                        "code_fragments": [
                            {"id": "frag1", "code": "match", "correct": True, "hint": "正确！使用match表达式"},
                            {"id": "frag2", "code": "switch", "correct": False, "hint": "Rust没有switch"},
                            {"id": "frag3", "code": "if", "correct": False, "hint": "if用于条件判断，不是模式匹配"},
                            {"id": "frag4", "code": "case", "correct": False, "hint": "case是match内的分支"}
                        ],
                        "correct_answer": ["match"],
                        "explanation": "match表达式允许将值与一系列模式进行比较，并执行匹配的模式对应的代码。",
                        "unlocked": True
                    }
                ]
            },
            "iterators": {
                "title": "迭代器",
                "description": "学习Rust的迭代器模式",
                "levels": [
                    {
                        "id": "iterators_1",
                        "title": "迭代器基础",
                        "description": "理解迭代器的创建和使用",
                        "difficulty": 1,
                        "code_template": [
                            "fn main() {",
                            "    let v = vec![1, 2, 3];",
                            "    ",
                            "    let v1 = v.iter().map(|x| x + 1)._____();",
                            "    ",
                            "    assert_eq!(v1, vec![2, 3, 4]);",
                            "}"
                        ],
                        "code_fragments": [
                            {"id": "frag1", "code": "collect", "correct": True, "hint": "正确！使用collect收集结果"},
                            {"id": "frag2", "code": "gather", "correct": False, "hint": "没有gather方法"},
                            {"id": "frag3", "code": "sum", "correct": False, "hint": "sum会求和，不是收集"},
                            {"id": "frag4", "code": "fold", "correct": False, "hint": "fold用于折叠，不是收集"}
                        ],
                        "correct_answer": ["collect"],
                        "explanation": "迭代器是惰性的，需要使用collect()方法来消费迭代器并收集结果。",
                        "unlocked": True
                    }
                ]
            },
            "generics": {
                "title": "泛型编程",
                "description": "学习Rust的泛型系统",
                "levels": [
                    {
                        "id": "generics_1",
                        "title": "泛型函数基础",
                        "description": "理解泛型函数的定义和使用",
                        "difficulty": 2,
                        "code_template": [
                            "fn largest<T: _____>(list: &[T]) -> T {",
                            "    let mut largest = list[0];",
                            "    for &item in list.iter() {",
                            "        if item > largest {",
                            "            largest = item;",
                            "        }",
                            "    }",
                            "    largest",
                            "}",
                            "",
                            "fn main() {",
                            "    let number_list = vec![34, 50, 25, 100, 65];",
                            "    let result = largest(&number_list);",
                            "    println!(\"The largest number is {}\", result);",
                            "}"
                        ],
                        "code_fragments": [
                            {"id": "frag1", "code": "PartialOrd", "correct": True, "hint": "正确！需要可比较trait"},
                            {"id": "frag2", "code": "Ord", "correct": False, "hint": "PartialOrd更基础"},
                            {"id": "frag3", "code": "Clone", "correct": False, "hint": "不需要克隆"},
                            {"id": "frag4", "code": "Copy", "correct": False, "hint": "不需要复制"}
                        ],
                        "correct_answer": ["PartialOrd"],
                        "explanation": "使用泛型参数T: PartialOrd确保类型可以进行比较操作。",
                        "unlocked": True
                    }
                ]
            },
            "modules": {
                "title": "模块系统",
                "description": "学习Rust的模块和包管理",
                "levels": [
                    {
                        "id": "modules_1",
                        "title": "模块基础",
                        "description": "理解模块的定义和使用",
                        "difficulty": 1,
                        "code_template": [
                            "mod _____ {",
                            "    pub fn function() {",
                            "        println!(\"This is a function in a module\");",
                            "    }",
                            "}",
                            "",
                            "fn main() {",
                            "    my_module::function();",
                            "}"
                        ],
                        "code_fragments": [
                            {"id": "frag1", "code": "my_module", "correct": True, "hint": "正确！模块名称"},
                            {"id": "frag2", "code": "module", "correct": False, "hint": "不是关键字"},
                            {"id": "frag3", "code": "namespace", "correct": False, "hint": "Rust使用mod不是namespace"},
                            {"id": "frag4", "code": "lib", "correct": False, "hint": "lib是库，不是模块"}
                        ],
                        "correct_answer": ["my_module"],
                        "explanation": "使用mod关键字定义模块，使用pub关键字使函数对外可见。",
                        "unlocked": True
                    }
                ]
            },
            "smart-pointers": {
                "title": "智能指针",
                "description": "学习Rust的智能指针类型",
                "levels": [
                    {
                        "id": "smart-pointers_1",
                        "title": "Box智能指针",
                        "description": "理解Box<T>的使用场景",
                        "difficulty": 2,
                        "code_template": [
                            "fn main() {",
                            "    let b = _____::new(5);",
                            "    println!(\"b = {}\", b);",
                            "}"
                        ],
                        "code_fragments": [
                            {"id": "frag1", "code": "Box", "correct": True, "hint": "正确！Box智能指针"},
                            {"id": "frag2", "code": "Rc", "correct": False, "hint": "Rc用于共享所有权"},
                            {"id": "frag3", "code": "Arc", "correct": False, "hint": "Arc用于线程安全的共享"},
                            {"id": "frag4", "code": "RefCell", "correct": False, "hint": "RefCell用于内部可变性"}
                        ],
                        "correct_answer": ["Box"],
                        "explanation": "Box<T>用于在堆上分配值，常用于递归类型或大值转移。",
                        "unlocked": True
                    }
                ]
            },
            "unsafe-rust": {
                "title": "Unsafe Rust",
                "description": "学习Rust的不安全代码块",
                "levels": [
                    {
                        "id": "unsafe-rust_1",
                        "title": "Unsafe基础",
                        "description": "理解unsafe关键字的使用",
                        "difficulty": 3,
                        "code_template": [
                            "fn main() {",
                            "    let mut num = 5;",
                            "",
                            "    let r1 = &num as *const i32;",
                            "    let r2 = &mut num as *mut i32;",
                            "",
                            "    _____ {",
                            "        println!(\"r1 is: {}\", *r1);",
                            "        println!(\"r2 is: {}\", *r2);",
                            "    }",
                            "}"
                        ],
                        "code_fragments": [
                            {"id": "frag1", "code": "unsafe", "correct": True, "hint": "正确！unsafe代码块"},
                            {"id": "frag2", "code": "raw", "correct": False, "hint": "不是关键字"},
                            {"id": "frag3", "code": "dangerous", "correct": False, "hint": "没有这个关键字"},
                            {"id": "frag4", "code": "ptr", "correct": False, "hint": "不是关键字"}
                        ],
                        "correct_answer": ["unsafe"],
                        "explanation": "使用unsafe关键字可以执行Rust通常禁止的操作，如解引用裸指针。",
                        "unlocked": True
                    }
                ]
            }
        }
    
    def get_available_challenges(self, user_id: str) -> Dict:
        """获取用户可用的挑战"""
        user_data = self.user_progress.get(user_id, {})
        completed_levels = set(user_data.get('completed_levels', []))
        
        result = {}
        for topic, topic_data in self.challenges.items():
            topic_levels = []
            for i, level in enumerate(topic_data['levels']):
                level_id = level['id']
                level_copy = level.copy()
                level_copy['is_completed'] = level_id in completed_levels
                # 第一个挑战默认解锁，或者根据unlocked标记，或者已完成
                is_unlocked = (i == 0) or level.get('unlocked', False) or level_id in completed_levels
                level_copy['is_unlocked'] = is_unlocked
                topic_levels.append(level_copy)
            
            result[topic] = {
                'title': topic_data['title'],
                'description': topic_data['description'],
                'levels': topic_levels,
                'progress': {
                    'total': len(topic_levels),
                    'completed': len([l for l in topic_levels if l['is_completed']]),
                    'unlocked': len([l for l in topic_levels if l['is_unlocked']])
                }
            }
        
        return result
    
    def get_challenge_by_id(self, challenge_id: str) -> Optional[Dict]:
        """根据ID获取具体挑战"""
        for topic, topic_data in self.challenges.items():
            for level in topic_data['levels']:
                if level['id'] == challenge_id:
                    return level.copy()
        return None
    
    def validate_answer(self, user_id: str, challenge_id: str, user_answers: List[str]) -> Dict:
        """验证用户答案"""
        challenge = self.get_challenge_by_id(challenge_id)
        if not challenge:
            return {
                'status': 'error',
                'message': '挑战不存在'
            }
        
        correct_answers = challenge.get('correct_answer', [])
        
        # 检查答案是否正确
        is_correct = len(user_answers) == len(correct_answers)
        if is_correct:
            for i, answer in enumerate(user_answers):
                if answer != correct_answers[i]:
                    is_correct = False
                    break
        
        if is_correct:
            # 更新用户进度
            if user_id not in self.user_progress:
                self.user_progress[user_id] = {'completed_levels': []}
            
            if challenge_id not in self.user_progress[user_id]['completed_levels']:
                self.user_progress[user_id]['completed_levels'].append(challenge_id)
                self._save_user_progress()
            
            # 解锁下一个关卡
            self._unlock_next_level(user_id, challenge_id)
            
            return {
                'status': 'success',
                'is_correct': True,
                'message': '恭喜通关！',
                'explanation': challenge.get('explanation', ''),
                'next_challenge': self._get_next_challenge(challenge_id)
            }
        else:
            # 提供提示
            hints = []
            for i, user_answer in enumerate(user_answers):
                if i < len(correct_answers) and user_answer != correct_answers[i]:
                    # 查找对应的片段提示
                    for fragment in challenge.get('code_fragments', []):
                        if fragment['code'] == user_answer:
                            hints.append(fragment.get('hint', '答案不正确'))
                            break
            
            return {
                'status': 'success',
                'is_correct': False,
                'message': '答案不正确，再试试看！',
                'hints': hints,
                'correct_answer': correct_answers
            }
    
    def _unlock_next_level(self, user_id: str, current_challenge_id: str):
        """解锁下一个关卡"""
        # 找到当前挑战所在的主题和索引
        for topic, topic_data in self.challenges.items():
            for i, level in enumerate(topic_data['levels']):
                if level['id'] == current_challenge_id:
                    # 如果存在下一个关卡，则解锁它
                    if i + 1 < len(topic_data['levels']):
                        next_level_id = topic_data['levels'][i + 1]['id']
                        # 直接修改挑战数据中的unlocked字段
                        self.challenges[topic]['levels'][i + 1]['unlocked'] = True
                        # 保存挑战数据
                        self._save_challenges(self.challenges)
                    return
    
    def _get_next_challenge(self, current_challenge_id: str) -> Optional[str]:
        """获取下一个挑战ID"""
        # 找到当前挑战所在的主题和索引
        for topic, topic_data in self.challenges.items():
            for i, level in enumerate(topic_data['levels']):
                if level['id'] == current_challenge_id:
                    # 如果存在下一个关卡，则返回其ID
                    if i + 1 < len(topic_data['levels']):
                        return topic_data['levels'][i + 1]['id']
                    # 如果是当前主题的最后一个关卡，尝试找下一个主题的第一个关卡
                    topics = list(self.challenges.keys())
                    current_index = topics.index(topic)
                    if current_index + 1 < len(topics):
                        next_topic = topics[current_index + 1]
                        return self.challenges[next_topic]['levels'][0]['id']
                    break
        return None
    
    def get_user_progress(self, user_id: str) -> Dict:
        """获取用户进度"""
        return self.user_progress.get(user_id, {'completed_levels': []})
    
    def reset_user_progress(self, user_id: str):
        """重置用户进度"""
        if user_id in self.user_progress:
            del self.user_progress[user_id]
            self._save_user_progress()

# 全局实例
challenge_manager = CodeChallengeManager()